<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">











<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "9c84d93b"
    });
  daovoice('update');
  </script>












<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=6.1.0" color="#222">







<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>


<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="1. 运行时数据区域：线程私有：  程序计数器 虚拟机栈 本地方法栈  线程共享：  堆 方法区 直接内存   2.1 程序计数器程序计数器是一块较小的内存空间，可以看做是当前线程所执行的字节码的行号指示器。字节码解释器工作是通过改变这个计数器的值来选取下一条需要执行的字节码指令，分支、循环、跳转、异常处理、线程恢复等功能都需要依赖这个计数器。另外为了线程切换后能恢复到正确执行的位置，每条线程都需">
<meta name="keywords" content="java,jvm">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM基础知识">
<meta property="og:url" content="http://zhangsnke.gitee.io/2019/01/09/JVM基础知识/index.html">
<meta property="og:site_name" content="Zhangsnke&#39;s Blog">
<meta property="og:description" content="1. 运行时数据区域：线程私有：  程序计数器 虚拟机栈 本地方法栈  线程共享：  堆 方法区 直接内存   2.1 程序计数器程序计数器是一块较小的内存空间，可以看做是当前线程所执行的字节码的行号指示器。字节码解释器工作是通过改变这个计数器的值来选取下一条需要执行的字节码指令，分支、循环、跳转、异常处理、线程恢复等功能都需要依赖这个计数器。另外为了线程切换后能恢复到正确执行的位置，每条线程都需">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fz0a9ryd36j30co0bxt9i.jpg">
<meta property="og:image" content="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fz0637bagij30gn06yq2w.jpg">
<meta property="og:image" content="http://wx3.sinaimg.cn/mw690/0060lm7Tly1fz0cn7hi8sj30c707mmxh.jpg">
<meta property="og:image" content="http://wx3.sinaimg.cn/mw690/0060lm7Tly1fz0513zmkmj30m902k74f.jpg">
<meta property="og:image" content="http://wx1.sinaimg.cn/mw690/0060lm7Tly1fz05l9pmzsj313m099q3d.jpg">
<meta property="og:image" content="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fz0dpcmq3gj30k108taca.jpg">
<meta property="og:image" content="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fz0dwergo5j30k208n0up.jpg">
<meta property="og:updated_time" content="2019-01-09T09:10:19.102Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JVM基础知识">
<meta name="twitter:description" content="1. 运行时数据区域：线程私有：  程序计数器 虚拟机栈 本地方法栈  线程共享：  堆 方法区 直接内存   2.1 程序计数器程序计数器是一块较小的内存空间，可以看做是当前线程所执行的字节码的行号指示器。字节码解释器工作是通过改变这个计数器的值来选取下一条需要执行的字节码指令，分支、循环、跳转、异常处理、线程恢复等功能都需要依赖这个计数器。另外为了线程切换后能恢复到正确执行的位置，每条线程都需">
<meta name="twitter:image" content="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fz0a9ryd36j30co0bxt9i.jpg">






  <link rel="canonical" href="http://zhangsnke.gitee.io/2019/01/09/JVM基础知识/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>JVM基础知识 | Zhangsnke's Blog</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
<a href="https://github.com/zxk318www"><img style="position: absolute; top: 0; left: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Zhangsnke's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
          
  
  <li class="menu-item menu-item-home menu-item-active">
    <a href="/blog/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-about">
    <a href="/blog/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-tags">
    <a href="/blog/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-categories">
    <a href="/blog/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-archives">
    <a href="/blog/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
</li>

      

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zhangsnke.gitee.io/blog/2019/01/09/JVM基础知识/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Zhangsnke">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://wx1.sinaimg.cn/mw690/0060lm7Tly1fz2r82s43bj30u20u0ad9.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zhangsnke's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JVM基础知识</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-09T16:46:01+08:00">2019-01-09</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/blog/categories/java基础知识/" itemprop="url" rel="index"><span itemprop="name">java基础知识</span></a></span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2019/01/09/JVM基础知识/#comments" itemprop="discussionUrl">
                  <span class="post-meta-item-text">评论数：</span> <span class="post-comments-count valine-comment-count" data-xid="/blog/2019/01/09/JVM基础知识/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="1-运行时数据区域："><a href="#1-运行时数据区域：" class="headerlink" title="1. 运行时数据区域："></a>1. 运行时数据区域：</h3><p><img src="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fz0a9ryd36j30co0bxt9i.jpg" alt="图1|center"><br><em>线程私有：</em></p>
<ul>
<li>程序计数器</li>
<li>虚拟机栈</li>
<li>本地方法栈</li>
</ul>
<p><em>线程共享：</em></p>
<ul>
<li>堆</li>
<li>方法区</li>
<li>直接内存</li>
</ul>
<hr>
<h3 id="2-1-程序计数器"><a href="#2-1-程序计数器" class="headerlink" title="2.1 程序计数器"></a>2.1 程序计数器</h3><p><em>程序计数器是一块较小的内存空间，可以看做是当前线程所执行的字节码的行号指示器。字节码解释器工作是通过改变这个计数器的值来选取下一条需要执行的字节码指令，分支、循环、跳转、异常处理、线程恢复等功能都需要依赖这个计数器。另外为了线程切换后能恢复到正确执行的位置，每条线程都需要一个独立的程序计数器，各线程之间计数器互相不影响，独立存储，称这类内存区域为<font color="red">“线程私有”的内存。</font></em></p>
<p> <strong>程序计数器作用</strong></p>
<ol>
<li>字节码解释器通过改变程序计数器来依次读取指令，从而实现代码的流程控制，如：顺序执行、选择、循环、异常处理。</li>
<li>在多线程的情况下，程序计数器用于记录当前线程执行位置，从而当前线程被切回来的时候能够知道该线程上次运行到哪儿了。<br><strong>注意</strong><br>程序计数器是唯一不会出现<font color="red">OutOfMemoryError</font>的内存区域，它的生命周期随着线程的创建而创建，随着线程的结束而死亡。</li>
</ol>
<hr>
<h3 id="2-2-Java虚拟机栈"><a href="#2-2-Java虚拟机栈" class="headerlink" title="2.2 Java虚拟机栈"></a>2.2 Java虚拟机栈</h3><p><em>与程序计数器一样，Java虚拟机栈也是线程私有的，它的生命周期和线程相同，描述的是Java方法执行的内存模型。</em></p>
<p><em>Java内存可以粗糙的区分为堆内存（Heap）和栈内存（Stack）。其中栈就是现在说的虚拟机栈，或者说是虚拟机栈中局部变量表部分。(实际上，Java虚拟机栈是由一个个栈帧组成的，而每个栈帧中都有局部变量表、操作数栈、动态链接、方法出口信息)。</em></p>
<p><em>局部变量表主要存放了编译器可知对的各种数据类型（boolean、byte、char、short、int、float、long、double）、对象引用（reference类型，它不同于对象本身，可能是一个指向对象起始地址的引用指针，也可能是指向一个代表对象的句柄或其他榆于此对象相关的位置）。</em></p>
<p><em>Java虚拟机栈会出现两种异常：<font color="red">StackOverFlowError</font> 和  <font color="red">OutOfMemoryError</font></em>。</p>
<ul>
<li>StackOverFolwError：若Java虚拟机栈的内存大小不允许动态扩展，那么当线程请求栈的深度超过当前Java虚拟机栈的最大深度的时候，就会抛出 StackOverFlowError 异常。</li>
<li>OutOfMemoryError：若Java虚拟机栈的内存大小允许动态扩展，且当前线程请求栈时内存用完了，无法再动态扩展，此时会抛出 OutOfMemoryError 异常。</li>
</ul>
<p><em>Java虚拟机栈也是线程私有的，每个线程都会有各自的Java虚拟机栈，而且随着线程的创建而创建，随着线程的结束而死亡。</em></p>
<hr>
<h3 id="2-3-本地方法栈"><a href="#2-3-本地方法栈" class="headerlink" title="2.3 本地方法栈"></a>2.3 本地方法栈</h3><p><em>和虚拟机栈发挥的作用非常类似，区别是：虚拟机栈为虚拟机执行Java方法（也就是字节码）服务，而本地方法栈则为虚拟机使用到的Native服务，在 HotSpot 虚拟机中和 Java 虚拟机栈合二为一。</em></p>
<p><em>本地方法被执行时候，在本地方法栈中会创建一个栈帧，用于存放该本地方法的局部变量表、操作数栈、动态链接、出口信息。</em></p>
<p><em>方法执行完后响应的栈帧会出栈并释放内存空间，也会出现 StackOverFlowError 和 OutOfMemoryError 两种异常。</em></p>
<hr>
<h3 id="2-4-堆"><a href="#2-4-堆" class="headerlink" title="2.4 堆"></a>2.4 堆</h3><p><em>Java虚拟机所管理的内存中最大一块，Java堆是所有线程共享的一块内存区域，在虚拟机启东时创建。此内存区域的唯一目的就是存放对象实例，几乎所有的对象实例以及数组都在这里分配内存。</em></p>
<p><em>Java堆是垃圾收集器管理的主要区域，因此也被称作 GC 堆（ Garbage Collected Heap ）。从垃圾回收的角度，由于现在收集器基本都采用分代垃圾收集算法，所以Java堆还可以细分为：新生代和老年代；再细致一点：Eden空间、From Survivor、To Survivor空间等。进一步的划分目的是为了更好的回收内存，或者更快的分配内存。</em></p>
<p><img src="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fz0637bagij30gn06yq2w.jpg" alt="图2"></p>
<p><em>在JDK1.8中移除了整个永久代，取而代之的是一个叫元空间（Metaspace）的区域（永久代使用的是JVM的堆内存空间，而元空间使用的是物理内存，直接受到本机的物理内存限制）。</em></p>
<p><a href="http://www.cnblogs.com/paddix/p/5309550.html" target="_blank" rel="noopener">Java8内存模型——永久代（PermGen）和元空间（Metaspace）</a></p>
<hr>
<h3 id="2-5-方法区"><a href="#2-5-方法区" class="headerlink" title="2.5 方法区"></a>2.5 方法区</h3><p><em>方法区和 Java 堆一样，是各个线程共享的内存区域，它用于存储已被虚拟机加载的类信息、常量、静态变量、即时编译器编译后的代码等数据。虽然Java虚拟机规范把方法区描述为堆一个逻辑部分，但它却又一个别名叫做 Non-Heap（非堆），目的应该是与 Java 堆区分开来。</em></p>
<p><em>HotSpot 虚拟机中方法区也常被称为“永久代”，本质上两者并不等价，仅仅因为 HotSpot 虚拟机设计团队用永久代来实现方法区而已，这样 HotSpot 虚拟机的垃圾收集器就可以像管理Java堆一样管理这部分的内存，但是这样容易遇到内存溢出问题。相对而言，垃圾收集行为在这个区域比较少出现，当并非数据进入了方法区就是“永久存在”的。</em></p>
<hr>
<h3 id="2-6-运行时常量池"><a href="#2-6-运行时常量池" class="headerlink" title="2.6 运行时常量池"></a>2.6 运行时常量池</h3><p><em>运行时常量池是方法区的一部分。Class文件中除了有类的版本、字段、方法、接口等描述信息外，还有常量池信息（用于存放编译期间产生的各种字面量和符号引用）。</em></p>
<p><em>既然运行时常量池时方法区的一部分，自然受到方法区内存的限制，当常量池无法再申请到内存时会抛出 OutOfMemoryError 异常。</em></p>
<p><em>JDK1.7及之后版本的 JVM 已经将运行时常量池从方法区中移了出来，在 Java 堆（Heap）中开辟了一块区域存放运行时常量池。</em><br><img src="http://wx3.sinaimg.cn/mw690/0060lm7Tly1fz0cn7hi8sj30c707mmxh.jpg" alt="图3|center"><br><a href="https://blog.csdn.net/qq_26222859/article/details/73135660" target="_blank" rel="noopener">Java中集中常量池的区分</a></p>
<hr>
<h3 id="2-7-直接内存"><a href="#2-7-直接内存" class="headerlink" title="2.7 直接内存"></a>2.7 直接内存</h3><p><em>直接内存并不是虚拟机运行时数据区的一部分，也不是虚拟机规范中定义的内存区域，但是这部分的内存也被频繁使用，而且也可能导致 OutOfMemoryError 异常。</em></p>
<p><em>JDK1.4中新加入的 NIO(New Input/Output) 类，引入了一种基于通信（Channel）与缓存区（Buffer）的 I/O 方式，它可以直接使用Native函数库直接分配堆外内存，然后通过一个存储在Java堆中的 DirectByteBuffer 对象作为这块内存的引用进行操作，这样可以在一些场景中显著提高性能，避免了 Java 堆和 Native 堆之间来回复制数据。</em></p>
<p><em>本机直接内存的分配不会受到Java堆的限制，但是，既然是内存就会受到本机总内存大小以及处理器寻址空间的限制。</em></p>
<hr>
<h3 id="3-java-创建对象过程："><a href="#3-java-创建对象过程：" class="headerlink" title="3.java 创建对象过程："></a>3.java 创建对象过程：</h3><p><img src="http://wx3.sinaimg.cn/mw690/0060lm7Tly1fz0513zmkmj30m902k74f.jpg" alt="图2"></p>
<p><strong>1.类加载检查</strong></p>
<p><em>虚拟机遇到new指令，首先检查这个指令的参数能否在常量池中定位到这个类的符号引用，并且检查这个符号引用代表的类是否已被加载过、解析和初始化过。如果没有，那必须执行相应的类加载过程。</em></p>
<p><strong>2.分配内存</strong></p>
<p><em>在类加载检查通过后，接下来虚拟机将为新生对象分配内存。对象所需要的内存大小在类加载完后可以确定。为对象分配空间的认为等同于把一块确定大小的内存从Java堆中划分出来，分配的方式有 <font color="red">“碰撞指针”</font>和“<font color="red">空闲列表”</font>两种。选择哪种分配方式由Java堆是否规整决定，Java堆是否规整由<font color="red">所采用的垃圾收集器是否带有压缩整理功能</font>决定。</em></p>
<ul>
<li><p>内存分配的两种方式<br><img src="http://wx1.sinaimg.cn/mw690/0060lm7Tly1fz05l9pmzsj313m099q3d.jpg" alt="图3"></p>
</li>
<li><p>内存分配并发问题<br> 在创建对象的时候需要保证线程安全，一般虚拟机采用以下两种方式：<br><strong>1.CAS+失败重试：</strong><br> CAS是乐观锁的一种实现方式。所谓乐观锁就是每次不加锁而是假设没有冲突去完成某项操作，如果因为冲突失败就重试，知道成功为止，虚拟机采用CAS配上失败重试的方式是为了保证操作的原子性。<br>  <strong>2.TLAB：</strong><br>  为每一个线程预先在Eden区分配一块内存。JVM在给线程中的对象分配内存时，首先在TLAB分配，当对象大于TLAB中的剩余内存或TLAB的内存已用尽时，再采用上述的CAS+失败重试进行内存分配。</p>
</li>
</ul>
<p><strong>3.初始化零值</strong></p>
<p><em>内存分配完成后，虚拟机需要将分配的内存空间都初始化零值（不包括对象头）。这一步操作保证了对象的实例字段在Java代码中可以不赋初始值就可以直接使用，程序访问到这些字段的数据类型所对应的零值。</em></p>
<p><strong>4.设置对象头</strong></p>
<p><em>初始化零值完成后，虚拟机需要对对象进行必要的设置，例如这个对象是哪个类的实例，如何才能找到类的元数据信息、对象的哈希码、对象的GC分代年龄等信息。这些信息都存放在对象头中。另外根据虚拟机当前运行状态的不同，如何启用偏向锁等，是否启用偏向锁等，对象头会有不同的设置方式。</em></p>
<p><strong>5.执行Init方法</strong></p>
<p><em>在上述工作完成后，从虚拟机的视角看，一个新的对象已经产生了，但从Java程序的视角看，对象创建才刚刚开始，Init方法还没有执行，所有的字段都还是零。所以一般来说，执行new指令之后会接着执行Init方法，把对象按照程序员的意愿进行初始化。</em></p>
<hr>
<h3 id="3-1-对象的内存布局"><a href="#3-1-对象的内存布局" class="headerlink" title="3.1 对象的内存布局"></a>3.1 对象的内存布局</h3><p><em>在 HotSpot 虚拟机中，对象在内存中的布局可以分为3块区域：对象头、实例数据和对齐填充。</em></p>
<p><em>HotSpot 虚拟机的对象头包括两部分信息：</em></p>
<ol>
<li>用于存储对象自身运行时数据（哈希码、GC分代年龄、锁状态标志等等）</li>
<li>类型指针，即对象指向它的类元数据的指针，虚拟机通过这个指针来确定这个对象是哪个类的实例。</li>
</ol>
<p><em>实例数据部分是对象真正存储的有效信息，也是在程序中所定义的各种类型的字段内容。</em></p>
<p><em>对齐填充部分不是必然存在的，也没有特别的含义，仅仅是占位作用。因为Hotspot虚拟机的自动内存管理系统要求对象起始地址必须是8字节的整数倍，换句话说就是对象的大小必须是8字节的整数倍。而对象头正好是8字节的倍数（1倍或2倍），因此对象实例数据部分没有对齐时，需要通过对齐填充来补全。</em></p>
<hr>
<h3 id="3-2-对象的访问定位"><a href="#3-2-对象的访问定位" class="headerlink" title="3.2 对象的访问定位"></a>3.2 对象的访问定位</h3><p><em>建立对象是为了使用对象，Java程序通过栈上的 reference 数据来操作堆上的具体对象。对象的访问方式有虚拟机实现而定，目前主流的访问方式有<font color="red">句柄</font> 和 <font color="red">指针</font>。</em> </p>
<ol>
<li><p><font color="bliue">句柄</font>：如果使用句柄的话，那么 Java 堆中将会划分出一块内存来作为句柄池，reference 中存储的就是对象的句柄地址，而句柄中包含了对象实例数据与类型数据各自的具体地址信息。<br><img src="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fz0dpcmq3gj30k108taca.jpg" alt="图4|center"></p>
</li>
<li><p><font color="bliue">直接指针</font>：如果使用直接指针访问，那么 Java 堆对象的布局中就必须要考虑如何防止访问类数据的相关信息，而reference 中存储的直接就是对象的地址。<br><img src="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fz0dwergo5j30k208n0up.jpg" alt="图5|center"></p>
</li>
</ol>
<p><em>这两种对象访问方式各有优势。使用句柄来访问的最大好处是 reference 中存的是稳定的句柄地址，在对象被移动时只改变句柄中的实例数据指针，而 reference 本身不需要修改。使用指针访问最大的好处就是速度快，节省了一次指针定位的时间开销。</em></p>
<hr>
<h3 id="4-String-类和常量池"><a href="#4-String-类和常量池" class="headerlink" title="4. String 类和常量池"></a>4. String 类和常量池</h3><p><strong>1. String 对象的两种创建方式:</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">String str1 = <span class="string">"abcd"</span>;</span><br><span class="line">String str2 = <span class="keyword">new</span> String(<span class="string">"abcd"</span>);</span><br><span class="line">System.out.print(str1==str2); <span class="comment">// false</span></span><br></pre></td></tr></table></figure>
<p><em>这两种创建方式有差别：第一种 str1 是从常量池中拿对象，第二种 str2 是直接在堆内存空间创建一个新的对象</em></p>
<p><strong><em>记住： 只要 new 方法，就需要创建新的对象。</em></strong></p>
<p><strong>2. String 类型的常量池比较特殊。</strong></p>
<ul>
<li>直接使用双引号声明出来的 String 对象会直接存储在常量池中。</li>
<li>如果不适用双引号声明的 String 对象，可以使用 String 提供的 intern 方法。String.intern( )是一个 Native 方法，它的作用是：如果运行时常量池已经包含了一个等于此 String 对象内容的字符串，则返回常量池中该字符串的引用；如果没有，则在常量池中创建与此 String 内容相同的字符串，并返回常量池中创建的字符串的引用。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">String s1 = <span class="keyword">new</span> String(<span class="string">"计算机"</span>);</span><br><span class="line">String s2 = s1.intern();</span><br><span class="line">String s3 = <span class="string">"计算机"</span>;</span><br><span class="line">System.out.print(s2);<span class="comment">//计算机</span></span><br><span class="line">System.out.print(s1 == s2);<span class="comment">//false,因为s1是一个堆内存的String对象，s2是常量池中的String对象</span></span><br><span class="line">System.out.print(s3 == s2);<span class="comment">//true,因为两个都是常量池中的String对象</span></span><br></pre></td></tr></table></figure>
<p><strong>3. String 字符串拼接</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">String str1 = <span class="string">"str"</span>;</span><br><span class="line">String str2 = <span class="string">"ing"</span>;</span><br><span class="line"></span><br><span class="line">String str3 = <span class="string">"str"</span> + <span class="string">"ing"</span>; <span class="comment">//常量池中的对象</span></span><br><span class="line">String str4 = str1 + str2; <span class="comment">//在堆上创建的新的对象</span></span><br><span class="line">String str5 = <span class="string">"string"</span>;<span class="comment">//常量池中的对象</span></span><br><span class="line">System.out.print(str3 == str4); <span class="comment">//false</span></span><br><span class="line">System.out.print(str3 == str5); <span class="comment">//true</span></span><br><span class="line">System.out.print(str4 == str5);<span class="comment">//false</span></span><br></pre></td></tr></table></figure></p>
<p><em>尽量避免对个字符串拼接，因为这样会重复创建对象。如果需要改变字符串的话，可以使用 StringBuilder （线程不安全）或者 StringBuffer（线程安全）。</em></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">String s1 = <span class="keyword">new</span> String(<span class="string">"abc"</span>);</span><br></pre></td></tr></table></figure>
<p>上述代码创建了两个对象。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">String s1 = <span class="keyword">new</span> String(<span class="string">"abc"</span>);<span class="comment">//堆内存的地址值</span></span><br><span class="line">String s2 = <span class="string">"abc"</span>;</span><br><span class="line">System.out.print(s1 == s2);<span class="comment">//false，以为一个是堆内存，一个是常量池的内存</span></span><br><span class="line">System.out.print(s1.equals(s2));<span class="comment">//true</span></span><br></pre></td></tr></table></figure>
<p><em>先有字符串 “abc” 放入常量池，然后 new了一份字符串 “abc” 放入 Java 堆（字符串常量 “abc” 在编译期间已经确定放入常量池，而 Java 堆上的 “abc” 是在运行初始化阶段确定），然后 Java 栈中的 s1指向 Java 堆上的 “abc”。</em></p>
<hr>
<h3 id="4-1-8种基本类型的包装和常量池"><a href="#4-1-8种基本类型的包装和常量池" class="headerlink" title="4.1 8种基本类型的包装和常量池"></a>4.1 8种基本类型的包装和常量池</h3><ul>
<li>java 基本类型的包装类大部分都实现了常量池技术，即 Byte 、Short 、Integer 、Long 、Character 、Boolean ；这六种包装类默认创建了数值 [-128,127]的相应的缓存数据，但是超出此范围仍然回去创建新的对象。</li>
<li>两种浮点数类型的包装类 Float、Double 并没有是实现常量池技术。</li>
<li><font color="red">PS: 所以包装类在比较是否相等时候，应该使用equals，而不是==。</font><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">Integer i1 = <span class="number">33</span>;</span><br><span class="line">Integer i2 = <span class="number">33</span>;</span><br><span class="line">System.out.println(i1 == i2);<span class="comment">// 输出true</span></span><br><span class="line">Integer i11 = <span class="number">333</span>;</span><br><span class="line">Integer i22 = <span class="number">333</span>;</span><br><span class="line">System.out.println(i11 == i22);<span class="comment">// 输出false</span></span><br><span class="line">Double i3 = <span class="number">1.2</span>;</span><br><span class="line">Double i4 = <span class="number">1.2</span>;</span><br><span class="line">System.out.println(i3 == i4);<span class="comment">// 输出false</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<p><em>Integer 缓存源代码：</em><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *此方法将始终缓存-128到127（包括端点）范围内的值，并可以缓存此范围之外的其他值。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Integer <span class="title">valueOf</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (i &gt;= IntegerCache.low &amp;&amp; i &lt;= IntegerCache.high)</span><br><span class="line">        <span class="keyword">return</span> IntegerCache.cache[i + (-IntegerCache.low)];</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Integer(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><em>应用场景：</em></p>
<ol>
<li>integer i1 = 40; Java在编译的时候会直接将代码封装成 Integer i1 = Integer.valueOf(40);从而使用常量池中的对象。</li>
<li><p>Integer i1 = new Integer(40)；这种情况下会创建新的对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Integer i1 = <span class="number">40</span>;</span><br><span class="line">Integer i2 = <span class="keyword">new</span> Integer(<span class="number">40</span>);</span><br><span class="line">System.out.println(i1==i2); <span class="comment">//输出false</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>Integer比较（==）</p>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">Integer i1 = <span class="number">40</span>;</span><br><span class="line">Integer i2 = <span class="number">40</span>;</span><br><span class="line">Integer i3 = <span class="number">0</span>;</span><br><span class="line">Integer i4 = <span class="keyword">new</span> Integer(<span class="number">40</span>);</span><br><span class="line">Integer i5 = <span class="keyword">new</span> Integer(<span class="number">40</span>);</span><br><span class="line">Integer i6 = <span class="keyword">new</span> Integer(<span class="number">0</span>);</span><br><span class="line"> </span><br><span class="line">System.out.println(<span class="string">"i1=i2   "</span> + (i1 == i2));</span><br><span class="line">System.out.println(<span class="string">"i1=i2+i3   "</span> + (i1 == i2 + i3));</span><br><span class="line">System.out.println(<span class="string">"i1=i4   "</span> + (i1 == i4));</span><br><span class="line">System.out.println(<span class="string">"i4=i5   "</span> + (i4 == i5));</span><br><span class="line">System.out.println(<span class="string">"i4=i5+i6   "</span> + (i4 == i5 + i6));   </span><br><span class="line">System.out.println(<span class="string">"40=i5+i6   "</span> + (<span class="number">40</span> == i5 + i6));</span><br><span class="line"><span class="comment">//结果</span></span><br><span class="line">i1=i2   <span class="keyword">true</span></span><br><span class="line">i1=i2+i3   <span class="keyword">true</span></span><br><span class="line">i1=i4   <span class="keyword">false</span></span><br><span class="line">i4=i5   <span class="keyword">false</span></span><br><span class="line">i4=i5+i6   <span class="keyword">true</span></span><br><span class="line"><span class="number">40</span>=i5+i6   <span class="keyword">true</span></span><br></pre></td></tr></table></figure>
<p><em>语句 i4 == i5 + i6; 因为 “+”这个操作符不适用于Integer对象，首先将i5和i6自动拆箱操作，进行数值相加，即 i4 = =40 ，然后 Integer对象无法与数值进行直接比较，所以将 i4 自动拆箱转为 int值 40 ，最终语句变成： 40 == 40进行数值比较。</em></p>

      
    </div>

    

    
    
    

<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
  
</div>

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fq7f9mgftqj30yf11x793.jpg" alt="Zhangsnke 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fq7f9yogljj30ox0qi76z.jpg" alt="Zhangsnke 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
          
            <a href="/blog/tags/jvm/" rel="tag"><i class="fa fa-tag"></i> jvm</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/04/12/java_api/" rel="next" title="java api调用">
                <i class="fa fa-chevron-left"></i> java api调用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/01/10/1. 简介：/" rel="prev" title="Java集合">
                Java集合 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="uyan_frame"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="http://wx1.sinaimg.cn/mw690/0060lm7Tly1fz2r82s43bj30u20u0ad9.jpg"
                alt="Zhangsnke" />
            
              <p class="site-author-name" itemprop="name">Zhangsnke</p>
              <p class="site-description motion-element" itemprop="description">java jsp</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/blog/archives/">
                
                    <span class="site-state-item-count">11</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/blog/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/blog/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">8</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/zxk318www" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:1137824821@qq.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/u/3487862312" target="_blank" title="Weibo"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-运行时数据区域："><span class="nav-number">1.</span> <span class="nav-text">1. 运行时数据区域：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-程序计数器"><span class="nav-number">2.</span> <span class="nav-text">2.1 程序计数器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-Java虚拟机栈"><span class="nav-number">3.</span> <span class="nav-text">2.2 Java虚拟机栈</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-本地方法栈"><span class="nav-number">4.</span> <span class="nav-text">2.3 本地方法栈</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-堆"><span class="nav-number">5.</span> <span class="nav-text">2.4 堆</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-5-方法区"><span class="nav-number">6.</span> <span class="nav-text">2.5 方法区</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-6-运行时常量池"><span class="nav-number">7.</span> <span class="nav-text">2.6 运行时常量池</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-7-直接内存"><span class="nav-number">8.</span> <span class="nav-text">2.7 直接内存</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-java-创建对象过程："><span class="nav-number">9.</span> <span class="nav-text">3.java 创建对象过程：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-对象的内存布局"><span class="nav-number">10.</span> <span class="nav-text">3.1 对象的内存布局</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-对象的访问定位"><span class="nav-number">11.</span> <span class="nav-text">3.2 对象的访问定位</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-String-类和常量池"><span class="nav-number">12.</span> <span class="nav-text">4. String 类和常量池</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-8种基本类型的包装和常量池"><span class="nav-number">13.</span> <span class="nav-text">4.1 8种基本类型的包装和常量池</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Zhangsnke</span>

  

  
</div>




<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>
  <!-- <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Muse</a> v6.1.0</div>
-->





<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共28.7k字</span>
</div>
        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=6.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2161053"></script>
      <!-- UY END -->
    
  





  








  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
  
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(function (item) {
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'V4OQTBV0QUJvAOnALRUDikMp-gzGzoHsz',
        appKey: 'Ygfy3JqhxL8KArimEFAGB3QQ',
        placeholder: 'ヾﾉ≧∀≦)o来啊，快活啊!',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
</body>
</html>

